/*****************************************************************
Mix3D WebGL Game Engine
Copyright (c) fantasy ( fantasy.x2x@gmail.com )
Listens:
Distributed under the Boost Software License, Version 1.0.
http://www.boost.org/LICENSE_1_0.txt
 ****************************************************************/
/**
 * @Desc    : plane 
 * @Author  : fantasy(fantasy.x2x@gmail.com)
 */
//////////////////////////////////////////////////////////////////
if(typeof(Mix3D) === 'undefined')
{
  Mix3D = {};
};
(function(Mix3D){
//////////////////////////////////////////////////////////////////
Mix3D.Plane = function(x,y,z, d)
{
  Mix3D.FloatArray.call(this,4);
  this.FA[0] = x||0;
  this.FA[1] = x||0;
  this.FA[2] = z||0;
  this.FA[3] = d||0;
};
Mix3D.Plane.prototype.constructor = Mix3D.Plane;
Mix3D.Plane.prototype.getNormal = function()
{
  return Mix3D.Plane._tempNormal.set(this.FA[0], this.FA[1], this.FA[2]);
};

Mix3D.Plane.prototype.set = function( x, y, z, d)
{
  this.FA[0]=x; this.FA[1]=y; this.FA[2]=z; this.FA[3]=d;
  return this;
};

Mix3D.Plane.prototype.getConstant = function()
{
  return this.FA[3];
};

Mix3D.Plane.prototype.setNormal = function( v )
{
  this.FA[0] = v.FA[0]; this.FA[1] = v.FA[1]; this.FA[2] = v.FA[2];
  return this;
};

Mix3D.Plane.prototype.setConstant = function( d )
{
  this.FA[3] = d;
  return this;
};

Mix3D.Plane.prototype.fromNormalAndPoint = function( normal, point )
{
  this.setNormal(normal);
  this.setConstant(normal.dot(point));
  return this;
};

Mix3D.Plane.prototype.fromPoints = function( a, b, c)
{
  var edge1 = Mix3D.Plane._tempV1.sub(b,a);
  var edge2 = Mix3D.Plane._tempV2.sub(c,a);
  Mix3D.Plane._tempNormal.cross(edge1, edge2).normalize();
  this.setNormal(Mix3D.Plane._tempNormal);
  this.setConstant(Mix3D.Plane._tempNormal.dot(a));
  return this;
};

Mix3D.Plane.prototype.distance = function( point )
{
  return (this.FA[0]*point.FA[0] +
          this.FA[1]*point.FA[1] + 
          this.FA[2]*point.FA[2]) - this.FA[3];
};

Mix3D.Plane.prototype.side = function( point )
{
  var dist = this.distance(point);
  if(dist<0)return -1; //back
  else if(dist>0)return 1; //front
  return 0; // onside
};

Mix3D.Plane.prototype.clone = function( other )
{
  return new Mix3D.Plane(this.FA[0], this.FA[1], this.FA[2], this.FA[3]);
};

Mix3D.Plane._tempNormal = new Mix3D.Vector3();
Mix3D.Plane._tempV1 = new Mix3D.Vector3();
Mix3D.Plane._tempV2 = new Mix3D.Vector3();
Mix3D.protoCopy(Mix3D.FloatArray, Mix3D.Plane);
//////////////////////////////////////////////////////////////////
})(Mix3D);// end of function(Mix3D)